/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppContext;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.bean.RunningAppInfo;

/**
 * @Title: ScoreService.java
 * @Package com.talben.soudian.service
 * @Description: 获取积分服务
 * @author Tal.Ben
 * @date 2015年6月1日 下午4:00:04
 * @version v1.0
 */
public class ScoreService extends Service {
	
	private String TAG = "ScoreService";

	private int i = 0;
	private String appname;
	private String id;
	private String pkgName;
	
	private String account;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	private PackageManager pm;
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags,int startId){
		//获取安装的路径
		Bundle bundle= intent.getExtras();
	    appname = bundle.getString("appname");//读出数据
	    account = bundle.getString("account");
	    id = bundle.getString("id");
	    pkgName = bundle.getString("pkgName");
	    
	    Handler handler = new Handler();
	    handler.postDelayed(new Runnable() {
            @Override
            public void run() {
        		if (openApp()) {
        			try {
						Thread.sleep(180000);
						SouDianAPI.getScore(account, id , mHandler);
					} catch (InterruptedException e) {
						stopSelf();
						e.printStackTrace();
					}
				} else {
					stopSelf();
				}
            	
            }
        }, 2000);
	    
		return startId;
	}
	
	
	private boolean openApp(){
//		List<RunningAppInfo> runningApp = queryAllRunningAppInfo();
//		for (int i = 0; i < runningApp.size(); i++) {
//			if (runningApp.get(i).getPkgName().equals("com.talben.soudian")) {
//				return true;
//			}
//		}
		return true;
	}
	
	// 查询所有正在运行的应用程序信息： 包括他们所在的进程id和进程名
	// 这儿我直接获取了系统里安装的所有应用程序，然后根据报名pkgname过滤获取所有真正运行的应用程序
	private List<RunningAppInfo> queryAllRunningAppInfo() {
		pm = this.getPackageManager();
		// 查询所有已经安装的应用程序
		List<ApplicationInfo> listAppcations = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
		Collections.sort(listAppcations,new ApplicationInfo.DisplayNameComparator(pm));// 排序
	
		// 保存所有正在运行的包名 以及它所在的进程信息
		Map<String, ActivityManager.RunningAppProcessInfo> pgkProcessAppMap = new HashMap<String, ActivityManager.RunningAppProcessInfo>();
	
		ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		// 通过调用ActivityManager的getRunningAppProcesses()方法获得系统里所有正在运行的进程
		List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager
				.getRunningAppProcesses();
	
		for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
	
			String[] pkgNameList = appProcess.pkgList; // 获得运行在该进程里的所有应用程序包
	
			// 输出所有应用程序的包名
			for (int i = 0; i < pkgNameList.length; i++) {
				String pkgName = pkgNameList[i];
				// 加入至map对象里
				pgkProcessAppMap.put(pkgName, appProcess);
			}
		}
		// 保存所有正在运行的应用程序信息
		List<RunningAppInfo> runningAppInfos = new ArrayList<RunningAppInfo>(); // 保存过滤查到的AppInfo
	
		for (ApplicationInfo app : listAppcations) {
			// 如果该包名存在 则构造一个RunningAppInfo对象
			if (pgkProcessAppMap.containsKey(app.packageName)) {
				// 获得该packageName的 pid 和 processName
				int pid = pgkProcessAppMap.get(app.packageName).pid;
				String processName = pgkProcessAppMap.get(app.packageName).processName;
				runningAppInfos.add(getAppInfo(app, pid, processName));
			}
		}
	
		return runningAppInfos;
	
	}
	
	
	// 构造一个RunningAppInfo对象 ，并赋值
	private RunningAppInfo getAppInfo(ApplicationInfo app, int pid, String processName) {
		RunningAppInfo appInfo = new RunningAppInfo();
		appInfo.setAppLabel((String) app.loadLabel(pm));
		appInfo.setAppIcon(app.loadIcon(pm));
		appInfo.setPkgName(app.packageName);
	
		appInfo.setPid(pid);
		appInfo.setProcessName(processName);
	
		return appInfo;
	}

	public static final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
            try {
				String msg = new String(arg2,"utf-8");
				AppContext.showToast(msg);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				String result = new String(arg2,"utf-8");
				JSONObject jObj = new JSONObject(result);
				if (jObj.getString("result").equals("success")) {
					AppContext.showToast("恭喜你，获取了"+jObj.getString("score")+"分");;
				}
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
    
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        Log.d(TAG, "onDestroy() executed");  
    }

}

